import akshare as ak
import re
import logging
import pandas as pd
from akshare_adapters import FinancialDataException, IndustryDataException

logger = logging.getLogger(__name__)

class AKShareFinancialsAdapter:
    """A股股票数据适配器（支持财务数据）"""
    
    def __init__(self, cache_enabled=True):
        self.cache_enabled = cache_enabled
        self.cache = {}

    @staticmethod
    def format_symbol(symbol: str) -> str:
        return re.sub(r"\.(SH|SZ)$", "", symbol)

    async def get_financials(self, symbol: str, item: str, periods=4) -> pd.DataFrame:
        """获取标准化财务数据"""
        cache_key = f"{symbol}_{item}"
        if self.cache_enabled and cache_key in self.cache:
            return self.cache[cache_key]

        try:
            formatted_symbol = self.format_symbol(symbol)
            if item == 'income':
                df = ak.stock_financial_report_sina(stock=formatted_symbol, symbol="利润表")
            elif item == 'balance':
                df = ak.stock_financial_report_sina(stock=formatted_symbol, symbol="资产负债表")
            elif item == 'cash_flow':
                df = ak.stock_financial_report_sina(stock=formatted_symbol, symbol="现金流量表")
            
            df = df.rename(columns={
                '净利润': 'net_profit',
                '股东权益合计': 'total_equity',
                '负债合计': 'total_liabilities',
                '经营活动现金流量净额': 'operating_cashflow',
                '现金及现金等价物净增加额': 'free_cashflow'
            }).sort_index().tail(periods)

            if self.cache_enabled:
                self.cache[cache_key] = df
            return df
            
        except Exception as e:
            logger.error(f"财务数据获取失败 {symbol}: {str(e)}")
            raise FinancialDataException(f"财务数据获取失败: {str(e)}")

    async def get_industry(self, symbol: str) -> str:
        """获取行业分类"""
        try:
            df = ak.stock_board_industry_sum_em()
            return df[df['代码'] == self.format_symbol(symbol)]['行业'].values[0]
        except Exception as e:
            logger.error(f"行业数据获取失败 {symbol}: {str(e)}")
            raise IndustryDataException(f"行业数据获取失败: {str(e)}")